package com.qf.springboot0406.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Component
@RestController
@RequestMapping("/test")
public class StuController {
    @Value("${stu.url}")
    String url;

    @GetMapping("/draw")
    public String draw2() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(url));

        //装没被抽到的数据的位置
        List<Integer> listSide = new ArrayList<>();
        //装全部数据的
        List<String> list = new ArrayList<>();

        //读取数据
        String flag;
        int side = 0;
        while ((flag = br.readLine())!=null){
            //保存原有数据
            list.add(flag);
            //没被抽到装这里
            if ((flag.split("="))[1].equals("0")){
                listSide.add(side);
            }
            side++;
        }
        //开始抽奖
        int size = listSide.size();
        if (size <= 0) {
            return "都抽完了,请重置";
        }
        //被抽中的
        int index = listSide.get((new Random()).nextInt(size));
        //抽取到的名字
        String name = (list.get(index)).split("=")[0];
        //修改文件里的标志
        list.set(index,name+"=1");
        //写回文件
        PrintWriter pw = new PrintWriter(new FileWriter(url));
        for (String s : list) {
            pw.println(s);
        }
        br.close();
        pw.close();
        return name;
    }

    //重置
    @GetMapping("/reset")
    public String reset2() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(url));
        //装修改后数据的
        List<String> list = new ArrayList<>();
        //一边读一边修改
        String flag;
        while ((flag = br.readLine())!=null){
            flag = flag.split("=")[0] + "=0";
            list.add(flag);
        }
        //写回文件
        PrintWriter pw = new PrintWriter(new FileWriter(url));
        for (String s : list) {
            pw.println(s);
        }
        br.close();
        pw.close();
        return "ok";
    }
}
